<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class FinanceController extends AdminbaseController{
    //账单详情
    public function finance_info(){
        $where_string = '';
        if(isset($_GET['customer_mobile'])){
            $_POST['customer_mobile'] = $_GET['customer_mobile'];
        }
        if(isset($_GET['type']) && $_GET['type'] == 1){
            $time_arr = getTimestampArr($_GET['value']);
            $recharge_where['recharge_time'] = $charge_where['charge_time']=array("BETWEEN","$time_arr[0],$time_arr[1]");
            $this->assign('type',$_GET['type']);
            $this->assign('value',$_GET['value']);
            $where_string = $where_string !='' ?$where_string." AND a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]" : "where a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]";
        }else{
            $recharge_where = $charge_where = true;
        }

        if((isset($_POST['customer_mobile']) && !empty($_POST['customer_mobile'])) || (isset($_GET['customer_mobile']) && !empty($_GET['customer_mobile']))){
            $recharge_where  = $charge_where = array();
            $customer_mobile = $_POST['customer_mobile'] ? $_POST['customer_mobile'] : I('get.customer_mobile');
            $customer_id = $recharge_where['customer_id'] = $charge_where['customer_id'] = getCustomerId($customer_mobile);
            $this->assign('mobile',$customer_mobile);
            $where_string = $where_string !='' ?$where_string." AND a.customer_id = '{$customer_id}' ":"where customer_id = '{$customer_id}'";
        }

        $Recharge_log = M('recharge_log');
        $Charge_log   = M('Charge_log');
        $Model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表

        $finance_info['recharge_customer_count'] = count($Recharge_log->where($recharge_where)->group('customer_id')->select());//充值客户数量
        $finance_info['recharge_money_sum']      = $Recharge_log->where($recharge_where)->getField("sum(recharge_money)");
        
        $finance_info['charge_money_sum']        = $Charge_log->where($charge_where)->getField("sum(charge_money)");
        
        
        $count  = ($Recharge_log->where($recharge_where)->count())+($Charge_log->where($charge_where)->count());
        $page   = $this->page($count, 15);
        
        $sql = $time_arr ? "select * from (select * from  bp_recharge_log  union all select * from bp_charge_log) a $where_string  order by a.recharge_time desc limit $page->firstRow, $page->listRows":" select * from  (select * from  bp_recharge_log  union all select * from bp_charge_log) a $where_string  order by a.recharge_time desc limit $page->firstRow, $page->listRows";
        $finance_list = $Model->query($sql);
        
     
        $this->assign('finance_list',$finance_list);
        $this->assign('finance_info',$finance_info);
        $this->assign("page", $page->show('Admin'));

        $this->display();
    }
    
	//账单列表
    public function finance_list(){
        //时间搜索限制
        $Recharge_log = M('Recharge_log');
        $Charge_log   = M('Charge_log');
        $Customer     = M('Customer');

        $where_string = '';
        if(isset($_GET['type']) && $_GET['type'] == 1){
            $time_arr = getTimestampArr($_GET['value']);
            $recharge_where['recharge_time'] = $charge_where['charge_time']=array("BETWEEN","$time_arr[0],$time_arr[1]");
            $this->assign('type',$_GET['type']);
            $this->assign('value',$_GET['value']);
            $where_string = $where_string !='' ?$where_string." AND a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]" : "where a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]";
        }else{
            $recharge_where = $charge_where = true;
        }

        if((isset($_POST['customer_mobile']) && !empty($_POST['customer_mobile'])) || (isset($_GET['customer_mobile']) && !empty($_GET['customer_mobile']))){
            $recharge_where  = $charge_where = array();
            $customer_mobile = I('post.customer_mobile') ? I('post.customer_mobile') : I('get.customer_mobile');
            $customer_id = $recharge_where['customer_id'] = $charge_where['customer_id'] = getCustomerId($customer_mobile);
            $this->assign('mobile',$customer_mobile);
            $where_string = $where_string !='' ?$where_string." AND a.customer_id = '{$customer_id}' ":"where customer_id = '{$customer_id}'";
        }
        
        $Model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
        $count = count($Model->query("select count(*) from (select * from  bp_recharge_log a union all select * from bp_charge_log) a $where_string group by a.customer_id"));
       
        $page  = $this->page($count, 15);
  
        $finance_list = $Model->query("select *from (select * from  bp_recharge_log  union all select * from bp_charge_log) a $where_string group by customer_id limit $page->firstRow, $page->listRows");
        
        foreach ($finance_list as $key => $val) {
            $where['customer_id'] = $val['customer_id'];

            $recharge_info  = $Recharge_log->where($where)->field('sum(recharge_money) as recharge_money_sum,max(recharge_time) as recharge_time_max')->find();
            $charge_info    = $Charge_log->where($where)->field('sum(charge_money) as charge_money,max(charge_time) as charge_time_max')->find();

            $finance_list[$key]['recharge_money_sum'] = $recharge_info['recharge_money_sum'] ? $recharge_info['recharge_money_sum'] : 0;
            $finance_list[$key]['recharge_time_max']  = $recharge_info['recharge_time_max']  ? date('Y-m-d H:i',$recharge_info['recharge_time_max']) : '---';
            $finance_list[$key]['charge_money_sum']   = $charge_info['charge_money_sum'] ? $charge_info['charge_money_sum'] : 0;
            $finance_list[$key]['charge_time_max']    = $charge_info['charge_time_max'] ? date('Y-m-d H:i',$charge_info['charge_time_max']) : '---';
            $finance_list[$key]['customer_info']      = $Customer->where('id ='.$val['customer_id'])->field('customer_name,mobile,money')->find();
        
        }

        $finance_info['recharge_money_sum'] = $Recharge_log->where($recharge_where)->getField('sum(recharge_money)');
        $finance_info['charge_money_sum']   = $Charge_log->where($charge_where)->getField('sum(charge_money)');
        $finance_info['customer_count']     = $count;
       
        // $customer_list = $Customer->limit($page->firstRow, $page->listRows)->order('id desc')->field('id,customer_name,mobile,money')->select();
        
        // foreach ($customer_list as $key => $val) {
        //     $charge_info = $Charge_log->where('customer_id = '.$val['id'])->field('sum(charge_money) as sum_charge_money,max(charge_time) as max_charge_time')->find();
        //     $customer_list[$key]['sum_charge_money'] = $charge_info['sum_charge_money'] ? $charge_info['sum_charge_money'] : 0;
        //     $customer_list[$key]['max_charge_time']  = $charge_info['max_charge_time']  ? date('Y-m-d H:i',$charge_info['max_charge_time'])  : '---';
        //     $recharge_info = $Recharge_log->where('customer_id = '.$val['id'])->field('sum(recharge_money) as sum_recharge_money,max(recharge_time) as max_recharge_time')->find();
            
        //     $customer_list[$key]['sum_recharge_money'] = $charge_info['sum_recharge_money'] ? $charge_info['sum_recharge_money'] : 0;
        //     $customer_list[$key]['max_recharge_time']  = $charge_info['max_recharge_time']  ? date('Y-m-d H:i',$charge_info['max_recharge_time'])  : '---';
        // }

        // //统计客户总数量，充值客户数量，充值总金额，消费总金额
        // $finance_total['customer_count'] = $count;
        // $finance_total['recharge_customer_count'] = $Recharge_log->group('customer_id')->count();
        // $finance_total['recharge_money_sum'] = $Recharge_log->getField('sum(recharge_money)');
        // $finance_total['charge_money_sum']   = $Charge_log->getField('sum(Charge_money)');

        $this->assign('finance_info',$finance_info);
        $this->assign('list',$finance_list);
        $this->assign("page", $page->show('Admin'));


        // $where_string = '';
        // if(isset($_GET['type']) && $_GET['type'] == 1){
        //     $time_arr = getTimestampArr($_GET['value']);
        //     $recharge_where['recharge_time'] = $charge_where['charge_time']=array("BETWEEN","$time_arr[0],$time_arr[1]");
        //     $this->assign('type',$_GET['type']);
        //     $this->assign('value',$_GET['value']);
        //     $where_string = $where_string !='' ?$where_string." AND a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]" : "where a.recharge_time BETWEEN $time_arr[0] AND $time_arr[1]";
        // }else{
        //     $recharge_where = $charge_where = true;
        // }

        // if((isset($_POST['customer_mobile']) && !empty($_POST['customer_mobile'])) || (isset($_GET['customer_mobile']) && !empty($_GET['customer_mobile']))){
        //     $recharge_where  = $charge_where = array();
        //     $customer_mobile = I('post.customer_mobile') ? I('post.customer_mobile') : I('get.customer_mobile');
        //     $customer_id = $recharge_where['customer_id'] = $charge_where['customer_id'] = getCustomerId($customer_mobile);
        //     $this->assign('mobile',$customer_mobile);
        //     $where_string = $where_string !='' ?$where_string." AND a.customer_id = '{$customer_id}' ":"where customer_id = '{$customer_id}'";
        // }

        // $Recharge_log = M('recharge_log');
        // $Charge_log   = M('Charge_log');
        // $Model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表

        // $finance_info['recharge_customer_count'] = count($Recharge_log->where($recharge_where)->group('customer_id')->select());//充值客户数量
        // $finance_info['recharge_money_sum']      = $Recharge_log->where($recharge_where)->getField("sum(recharge_money)");
        
        // $finance_info['charge_money_sum']        = $Charge_log->where($charge_where)->getField("sum(charge_money)");
        
        
        // $count  = ($Recharge_log->where($recharge_where)->count())+($Charge_log->where($charge_where)->count());
        // $page   = $this->page($count, 15);
        
        // $sql = $time_arr ? "select * from (select * from  bp_recharge_log  union all select * from bp_charge_log) a $where_string  order by a.recharge_time desc limit $page->firstRow, $page->listRows":"select * from  bp_recharge_log a union all select * from bp_charge_log $where_string  order by recharge_time desc limit $page->firstRow, $page->listRows";
        
        // $finance_list = $Model->query($sql);
        
     
        // $this->assign('finance_list',$finance_list);
        // $this->assign('finance_info',$finance_info);
        // $this->assign("page", $page->show('Admin'));

        $this->display();
    }
	// public function finance_list(){
 //        $where['year']  = isset($_GET['year'])  ? I('get.year')  : date('Y',time());
 //        $where['month'] = isset($_GET['month']) ? I('get.month') : date('m',time());
 //        if(isset($_POST['customer_mobile']) && !empty($_POST['customer_mobile'])){
 //            $where['customer_mobile'] = I('post.customer_mobile');
 //            $this->assign('customer_mobile',$where['customer_mobile']);
 //        }
 //        if(isset($_POST['user_date'])){
 //            $date = explode('-',I('post.user_date'));
 //            $where['year']  = $date[0];
 //            $where['month'] = $date[1];
 //            $this->assign('user_date',$user_date);
 //        }
 //        $finance_list = M('Finance')->where($where)->select();
   
 //        $this->assign('list',$finance_list);
	// 	$this->display();
	// }

    //账单详情信息
    // public function finance_info(){
    //     $Finance      = M('Finance');
    //     $id           = (int)$_GET['id'];
    //     $result       = $Finance->where('id = '.$id)->field('year,month,customer_mobile')->find();
    //     $now_month    = strtotime($result['year'].'-'.$result['month'].'-10');//当前月10号的时间戳
    //     $last_month   = strtotime("$now_month -1 month");//上个月10号的时间戳
        
       
      
    //     if(isset($_POST['user_date'])){
    //         $user_date    = explode('-', I('post.user_date'));
    //         $now_month    = strtotime($user_date[0].'-'.$user_date[1].'-10');//当前月10号的时间戳
    //         $last_month   = strtotime("$now_month -1 month");//上个月10号的时间戳
    //     }
    //     if(isset($_POST['customer_mobile']) && $_POST['customer_mobile'] !=''){
    //         $result['customer_mobile'] = I('post.customer_mobile');
    //     }

    //     $where['customer_mobile'] = $result['customer_mobile'];
    //     $where['use_time'] = array('BETWEEN',"$last_month,$now_month");
    //     $consumption_list  = M('Consumption')->where($where)->field('id,event_name,use_time,auth_code,scoreboard_ip,wx_nick_name,wx_avatar_url,wx_openid')->order('event_name,use_date asc')->select();
        
    //     $result['month']   = $result['month'] < 10 ? '0'.$result['month'] : $result['month'];
    //     $user_date = isset($_POST['user_date']) ? I('post.user_date') : $result['year'].'-'.$result['month'];
       
    //     $this->assign('user_date',$user_date);
    //     $this->assign('customer_mobile',$where['customer_mobile']);
    //     $this->assign('list',$consumption_list);
    //     $this->display();
    // }

	//生成账单
	public function createFinance(){
		
		$Finance     = M('finance');
		$Consumption = M('Consumption'); 
	    $year    = (int)I('post.year');
		$month   = (int)I('post.month');
		$now_month    = strtotime($year.'-'.$month.'-10');//当前月10号的时间戳
		$last_month   = strtotime("$now_month -1 month");//上个月10号的时间戳
        if(!$Finance->where('year = '.$year.' AND '.'month = '.$month)->find()){
            //查询该时间的段的计费信息
            $where['use_time'] = array('BETWEEN',"$last_month,$now_month");
            $consumption_list  = $Consumption->where($where)->field('customer_mobile,customer_name,count(use_date) as sum_use_date,count(wx_openid) as sum_use_number')->group('customer_mobile')->select();
            foreach ($consumption_list as $key => $val) {
            	$where['customer_mobile'] = $val['customer_mobile']; 
            	$event_list = $Consumption->where($where)->field('event_id,event_name,auth_code')->group('event_id')->select();
                $consumption_list[$key]['event_list'] =serialize($event_list);
                $consumption_list[$key]['year']       = $year;
                $consumption_list[$key]['month']      = $month;
            }
            if($Finance->addAll($consumption_list)){
            	$data['status']= 1;
            	$data['info'] = '该月账单生成成功！';
            	$data['url' ] = U('Finance/finance_list',array('year'=>$year,'month'=>$month));
            }
        }else{
        	$data['status'] = 2;
        	$data['info']  = '该月账单已经生成，不能重复生成！';
        }
        $this->ajaxReturn($data);
		
		// $user_date   = date('Y-m-10',strtotime(I('post.user_date')));
		// $now_mouth   = $user_date[0].'-'.$user_date[1].'-10';
  //       $last_mouth  = date('Y-m-d',strtotime("$now_mouth -1 month  day"));
		// $this->ajaxReturn($user_date);
        
	}
	
	//账户充值
	public function recharge(){
        if(isset($_GET['mobile'])) $this->assign('mobile',I('get.mobile'));
        
		if(IS_POST){
			$Customer = M("customer");
			$mobile = I('post.mobile');
			$money  = I('post.money');
			$recharge_type = I('post.recharge_type');
            //验证手机号
            if($result = $Customer->where(array('mobile'=>$mobile))->find()){
                $update_info['money']  = (int)$result['money']+$money;
                $where['id'] = $result['id'];
                $update_info['status'] = ($result['status'] == 2 && $update_info['money'] >=0) ? 1 : $result['status']; 

                if($Customer->where($where)->save($update_info)){
                    //添加充值记录
                    $result = $this->addRechargeLog($mobile,$money,$recharge_type);
                    addActionLog('recharge',$result);
                	$this->success("充值成功",U("Finance/recharge"));
         
                }else{
                	$this->error("充值失败！");
                }
            }else{
            	$this->error("不存在该客户！");
            }
		}else{
            $System_config = D('Common/SystemConfig');
            $this->assign('recharge_type_list',$System_config->getSystemConfigItem('recharge_type'));
            $this->display();
		}
	}

	//充值记录列表页
	public function recharge_log(){
        $Recharge_log = M('recharge_log');

        if(!empty($_POST['customer_mobile'])) $where['r.customer_mobile'] = I('post.customer_mobile');
        $this->assign('mobile',$where['r.customer_mobile']);

        $count  = $Recharge_log->alias('r')->where($where)->count();
        $page   = $this->page($count, 15);

		$list   = $Recharge_log->alias('r')
                               ->join('__CUSTOMER__ c on c.mobile = r.customer_mobile','left')
                               ->where($where)
                               ->order('r.recharge_time desc')
                               ->limit($page->firstRow, $page->listRows)
                               ->field('r.id,r.recharge_money,r.recharge_time,r.recharge_type,c.customer_name,c.mobile as customer_mobile,c.money')
                               ->select();
		$this->assign('list', $list);
        $this->assign("page", $page->show('Admin'));

		$this->display();
	}

    
    public function addRechargeLog($mobile,$money,$recharge_type){
        $customer_info                    = M('Customer')->where('mobile = '.$mobile)->field('id,customer_name')->find();
        $recharge_info['customer_name']   = $customer_info['customer_name'];
        $recharge_info['customer_id']     = $customer_info['id'];
        $recharge_info['customer_mobile'] = $mobile;
        $recharge_info['recharge_money']  = $money;
        $recharge_info['recharge_type']   = $recharge_type;
        $recharge_info['recharge_time']   = time();
        return M('recharge_log')->add($recharge_info);
    }

        //消费记录列表页
    public function charge_log(){
        $Charge_log = M('charge_log');

        if(!empty($_POST['customer_mobile'])) $where['a.customer_mobile'] = I('post.customer_mobile');
        $this->assign('mobile',$where['a.customer_mobile']);
        
        $count  = $Charge_log->alias('a')->where($where)->count();
        $page   = $this->page($count, 15);

        $list   = $Charge_log->alias('a')
                               ->join('__CUSTOMER__ c on c.mobile = a.customer_mobile','left')
                               ->where($where)
                               ->order('a.charge_time desc')
                               ->limit($page->firstRow, $page->listRows)
                               ->field('a.id,a.charge_money,a.charge_time,a.remarks,c.customer_name,c.mobile as customer_mobile,c.money')
                               ->select();
        $this->assign('list',$list);
        $this->assign("page", $page->show('Admin'));
        
        $this->display();
    }

    //消费
    public function charge(){

        if(IS_POST){
            $Customer = M("customer");
            $mobile = I('post.mobile');
            $money  = I('post.money');
            $remarks = I('post.remarks');
            //验证手机号
            if($result = $Customer->where(array('mobile'=>$mobile))->find()){
                $update_info['money'] = (int)$result['money']-$money;
                $where['id'] = $result['id'];

                if($update_info['money']>=0 && $Customer->where($where)->save($update_info)){
                    //添加充值记录
                    addActionLog('charge',$where['id']);
                    $this->addChargeLog($mobile,$money,$remarks);
                    $this->success("扣费成功",U("Finance/charge"));
         
                }else{
                    $this->error("扣费失败！账户余额不足！");
                }
            }else{
                $this->error("不存在该客户！");
            }
        }else{
            $this->display();
        }
    }

    public function addChargeLog($mobile,$money,$remarks){
        $customer_info                    = M('Customer')->where('mobile = '.$mobile)->field('id,customer_name')->find();
        $charge_info['customer_name']   = $customer_info['customer_name'];
        $charge_info['customer_id']     = $customer_info['id'];
        $charge_info['customer_mobile'] = $mobile;
        $charge_info['charge_money']  = $money;
        $charge_info['remarks']   = $remarks;
        $charge_info['charge_time']   = time();
        M('charge_log')->add($charge_info);
    }
	
}